package wsi.gui.predpath;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.rygh.core.html.table.HtmlTable;
import org.rygh.core.html.table.TableData;
import org.rygh.core.html.table.TableTuple;
import org.rygh.core.util.UIo;
import org.rygh.semantic.model.ex.PredicatePath;

import wsi.script.AppConfig;

public class PredicatePathTime {
	static class Tuple implements Comparable<Tuple> {
		double forward;
		double inverse;
		PredicatePath path;

		public Tuple(String line) {
			int pos = line.indexOf(':');
			forward = Double.parseDouble(line.substring(0, pos));

			int posb = line.indexOf(':', pos + 1);
			inverse = Double.parseDouble(line.substring(pos + 1, posb));

			path = new PredicatePath(line.substring(posb + 1));
		}

		@Override
		public int compareTo(Tuple o) {
			return (int) (1000 * o.getTime()) - (int) (1000 * getTime());
		}

		public double getTime() {
			return forward + inverse;
		}
	}

	private final List<Tuple> tuples = new ArrayList<>();

	public PredicatePathTime() {

	}

	public void load() {
		File file = new File(AppConfig.shared().getResourcesFolder(),
				"_debug_functionality_path_time.txt");

		if (!file.exists())
			return;

		String[] lines = UIo.readFile(file).split("\r\n");

		for (String line : lines)
			tuples.add(new Tuple(line));

		Collections.sort(tuples);
	}

	public String toHtmlString() {
		TableData data = new TableData();
		TableTuple tuple = new TableTuple();

		tuple.add("Total Time (s)", "Forward Time (s)", "Inverse Time(s)",
				"Predicate Path");
		data.add(tuple);

		for (Tuple t : tuples) {
			tuple = new TableTuple();
			tuple.add(String.format("%.2f", t.getTime()), t.forward, t.inverse, t.path.getKey());

			data.add(tuple);
		}

		HtmlTable table = new HtmlTable("Predicate Path Time", data);
		return table.toSimpleString();
	}
}
